package inet.app.vod.activity.account;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.dialog.MySpinnerDialogFragment;
import inet.app.vod.dialog.MySpinnerDialogFragment.SpinnerListener;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.object.User;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyPreferenceManager;
import inet.app.vod.util.MyUtil;
import inet.app.vod.view.AccountEditRowView;
import inet.app.vod.view.AccountEditRowView.EditListener;
import inet.app.vod.view.BoldTextView;
import inet.app.vod.view.ExpandCollapseAnimation;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.util.text.ValidateUtil;

public class AccountInfoActivity extends BaseActivity {

	private final static int REQUEST_CHANGE_PASSWORD = 1;

	private ImageView mAvatar;
	private LinearLayout mInfoLayout;
	private AccountEditRowView[] mEditViews;
	private MySpinnerDialogFragment mGenderDialog;
	private AlertDialog mLogoutDialog;

	private User mAccount;
	private MyPreferenceManager mPreference;
	private int mCurrentEditViewPosition;
	private String[] mGenders = new String[] { "Nữ", "Nam" };

	private View.OnClickListener updateListener = new View.OnClickListener() {

		@Override
		public void onClick(View arg0) {
			String emptyText = getString(R.string.chua_cap_nhat);

			// full name
			String fullName = mEditViews[1].getContent();
			if (fullName == null || fullName.equals(emptyText)) {
				mAccount.setFullname("");
			} else {
				mAccount.setFullname(mEditViews[1].getContent());
			}

			// email
			mAccount.setEmail(mEditViews[2].getContent());

			// phone number
			String phone = mEditViews[3].getContent();
			if (phone == null || phone.equals(emptyText)) {
				mAccount.setPhone("");
			} else {
				mAccount.setPhone(mEditViews[3].getContent());
			}

			VolleyClient.editAccount(mAccount, new VolleyListener(
					AccountInfoActivity.this) {

				@Override
				public void onSuccess(String response) {
					ResultJsonModel jResult = Parse.parseAccount(response);
					if (jResult == null) {
						// error parser
						MyUtil.showDialog("Lỗi server",
								AccountInfoActivity.this);
					} else if (jResult.hasError()) {
						// error edit
						MyUtil.showDialog("Lỗi cập nhật thông tin người dùng",
								AccountInfoActivity.this);
					} else {
						// save account to preference
						MyPreferenceManager.getInstance(
								AccountInfoActivity.this
										.getApplicationContext()).setAccount(
								mAccount);
						finish();
					}
				}

				@Override
				public void onStart() {
					Log.d("start request edit account " + mAccount.toString());
					showLoading(true);
				}

				@Override
				public void onFinish() {
					Log.d("finish request edit account");
					showLoading(false);
				}

				@Override
				public void onError(VolleyError error) {
					MyUtil.showDialog("Lỗi cập nhật thông tin người dùng ("
							+ error.getMessage() + ")",
							AccountInfoActivity.this);
				}
			});
		}
	};

	private void initModels() {

		mPreference = MyPreferenceManager.getInstance(getApplicationContext());
		mAccount = mPreference.getAccount();
	}

	private void initViews() {

		findViewById(R.id.update_btn).setOnClickListener(updateListener);

		mAvatar = (ImageView) findViewById(R.id.avatar_img);
		mEditViews = new AccountEditRowView[6];
		mInfoLayout = (LinearLayout) findViewById(R.id.info_layout);

		/************************ initialize info view ******************************/

		// ten dang nhap
		mEditViews[0] = new AccountEditRowView(this);
		mEditViews[0].setName(getString(R.string.ten_dang_nhap));
		mEditViews[0].setContent(getEmptyText(mAccount.getUsername()));
		mEditViews[0].setPositionInParentLayout(0);
		mEditViews[0].setEnableEdit(false);
		mInfoLayout.addView(mEditViews[0]);

		// ten day du
		mEditViews[1] = new AccountEditRowView(this);
		mEditViews[1].setName(getString(R.string.ten_day_du));
		mEditViews[1].setContent(getEmptyText(mAccount.getFullname()));
		mEditViews[1].setEditListener(new EditListener() {

			@Override
			public boolean validate() {
				return true;
			}

			@Override
			public void onEditBtnClick(int position) {
				editBtnClick(position);
			}
		});
		mEditViews[1].setPositionInParentLayout(1);
		mInfoLayout.addView(mEditViews[1]);

		// email
		mEditViews[2] = new AccountEditRowView(this);
		mEditViews[2].setName(getString(R.string.email));
		mEditViews[2].setContent(getEmptyText(mAccount.getEmail()));
		mEditViews[2].setEditListener(new EditListener() {

			@Override
			public boolean validate() {
				String email = mEditViews[2].mEditText.getText().toString();
				if (!ValidateUtil.validateEmail(email)) {
					mEditViews[2].mEditText
							.setError(getString(R.string.email_khong_hop_le));
					return false;
				}
				return true;
			}

			@Override
			public void onEditBtnClick(int position) {
				editBtnClick(position);
			}
		});
		mEditViews[2].setPositionInParentLayout(2);
		mInfoLayout.addView(mEditViews[2]);

		// so dien thoai
		mEditViews[3] = new AccountEditRowView(this);
		mEditViews[3].setName(getString(R.string.so_dien_thoai));
		mEditViews[3].setContent(getEmptyText(mAccount.getPhone()));
		mEditViews[3].mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
		mEditViews[3].setEditListener(new EditListener() {

			@Override
			public boolean validate() {
				String phone = mEditViews[3].mEditText.getText().toString();
				if (!ValidateUtil.validatePhoneNumber(phone)) {
					mEditViews[3].mEditText
							.setError(getString(R.string.sdt_khong_hop_le));
					return false;
				}
				return true;
			}

			@Override
			public void onEditBtnClick(int position) {
				editBtnClick(position);
			}
		});
		mEditViews[3].setPositionInParentLayout(3);
		mInfoLayout.addView(mEditViews[3]);

		// gioi tinh
		switchGender(mAccount.getGender());
		mGenderDialog = MySpinnerDialogFragment.newInstance("Giới tính",
				mGenders);
		mGenderDialog.setSpinnerListener(new SpinnerListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mGenderDialog.dismiss();
				mEditViews[4].setContent(mGenders[position]);
				switchGender(position);
			}
		});
		mEditViews[4] = new AccountEditRowView(this);
		mEditViews[4].setName(getString(R.string.gioi_tinh));
		if (mAccount.getGender() < 0) {
			mEditViews[4].setContent("Không xác định");
		} else {
			mEditViews[4].setContent(mGenders[mAccount.getGender()]);
		}
		mEditViews[4].mEditBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				removePreviousDialog("gender_spinner");
				if (mAccount.getGender() < 0) {
					mGenderDialog.setCurPosition(0);
				} else {
					mGenderDialog.setCurPosition(mAccount.getGender());
				}
				mGenderDialog.show(
						AccountInfoActivity.this.getSupportFragmentManager(),
						"gender_spinner");
			}
		});

		mEditViews[4].setEditListener(new EditListener() {

			@Override
			public boolean validate() {
				return true;
			}

			@Override
			public void onEditBtnClick(int position) {
				editBtnClick(position);

			}
		});
		mEditViews[4].setPositionInParentLayout(4);
		mInfoLayout.addView(mEditViews[4]);

		// doi mat khau
		BoldTextView changePwd = (BoldTextView) findViewById(R.id.changepwd);
		changePwd.setText(Html.fromHtml(new StringBuffer("<u>")
				.append(getString(R.string.doi_mat_khau)).append("</u>")
				.toString()));

		changePwd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString("old_pass", mAccount.getPassword());
				LaunchIntent.startForResult(AccountInfoActivity.this,
						PasswordChangeActivity.class, bundle,
						REQUEST_CHANGE_PASSWORD);
			}
		});

		setTitle(getString(R.string.thong_tin_tai_khoan));
	}

	private void switchGender(int gender) {
		mAccount.setGender(gender);
		if (gender == 0) {
			mAvatar.setImageResource(R.drawable.female);
		} else {
			mAvatar.setImageResource(R.drawable.male);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_info);
		initUIBase();
		initModels();
		initViews();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == REQUEST_CHANGE_PASSWORD) {

			if (resultCode == RESULT_OK) {
				String pwd = data.getStringExtra("result");
				Log.d("new pass " + pwd);
				mAccount.setPassword(pwd);
			} else {
				mAccount.setPassword("");
			}
		}
	}

	private void editBtnClick(int position) {
		if (position != mCurrentEditViewPosition) {
			if (mEditViews[mCurrentEditViewPosition].getEditLayoutVisiblily() == View.VISIBLE) {
				mEditViews[mCurrentEditViewPosition]
						.animateView(ExpandCollapseAnimation.COLLAPSE);
			}
			mCurrentEditViewPosition = position;
		}
	}

	private String getEmptyText(String text) {
		return (TextUtils.isEmpty(text) ? getString(R.string.chua_cap_nhat)
				: text);
	}

	@Override
	public void onResume() {
		super.onResume();
		setRightMenuHeader(R.drawable.icon_logout, new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				AlertDialog.Builder builder = new AlertDialog.Builder(
						AccountInfoActivity.this);
				// Add the buttons
				builder.setPositiveButton("Ok",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								mPreference.clearAccount();
								finish();
							}
						});
				builder.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								if (mLogoutDialog != null) {
									mLogoutDialog.dismiss();
								}
							}
						});
				builder.setTitle("Đăng xuất");
				builder.setMessage("Bạn muốn đăng xuất khỏi tài khoản này?");
				mLogoutDialog = builder.create();
				mLogoutDialog.show();
			}
		});
	}

	@Override
	public void setTagMenu() {
		mTagMenu = -1;
	}

}
